package com.fooddelivery;

import com.fooddelivery.dao.*;
import com.fooddelivery.model.*;
import com.fooddelivery.model.MenuItem;
import com.formdev.flatlaf.FlatLightLaf;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;

public class MainFrame extends JFrame {
    private JTable restaurantTable, orderTable, reviewTable;
    private DefaultTableModel restaurantTableModel, orderTableModel, reviewTableModel;
    private JComboBox<String> restaurantComboBox, menuItemComboBox;
    private JSpinner quantitySpinner;
    private JTextField ratingField;
    private JTextArea commentArea;
    private int userId;

    public MainFrame(int userId) {
        this.userId = userId;
        FlatLightLaf.setup(); // 使用 FlatLaf 美化界面
        setTitle("外卖点餐系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建标签页
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("餐厅浏览", createRestaurantPanel());
        tabbedPane.addTab("订餐", createOrderPanel());
        tabbedPane.addTab("订单管理", createOrderManagementPanel());
        tabbedPane.addTab("评价", createReviewPanel());
        tabbedPane.addTab("修改菜单", createMenuManagementPanel());
        tabbedPane.addTab("外卖派送", createDeliveryPanel()); // 添加外卖派送标签页

        add(tabbedPane);
    }

    private JPanel createRestaurantPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 表格模型
        restaurantTableModel = new DefaultTableModel(new String[]{"ID", "名称", "位置", "菜系"}, 0);
        restaurantTable = new JTable(restaurantTableModel);
        JScrollPane scrollPane = new JScrollPane(restaurantTable);

        // 加载餐厅数据
        loadRestaurants();

        panel.add(scrollPane, BorderLayout.CENTER);
        return panel;
    }

    private JPanel createOrderPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 餐厅选择
        JPanel inputPanel = new JPanel(new GridLayout(4, 2));
        inputPanel.add(new JLabel("餐厅:"));
        restaurantComboBox = new JComboBox<>();
        loadRestaurantsToComboBox();
        inputPanel.add(restaurantComboBox);

        inputPanel.add(new JLabel("菜单项:"));
        menuItemComboBox = new JComboBox<>();
        inputPanel.add(menuItemComboBox);

        inputPanel.add(new JLabel("数量:"));
        quantitySpinner = new JSpinner(new SpinnerNumberModel(1, 1, 10, 1));
        inputPanel.add(quantitySpinner);

        JButton placeOrderButton = new JButton("下单");
        placeOrderButton.addActionListener(e -> placeOrder());
        inputPanel.add(placeOrderButton);

        // 监听餐厅选择事件，动态加载菜单项
        restaurantComboBox.addActionListener(e -> loadMenuItemsByRestaurant());

        panel.add(inputPanel, BorderLayout.NORTH);
        return panel;
    }

    private JPanel createOrderManagementPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 表格模型
        orderTableModel = new DefaultTableModel(new String[]{"订单ID", "餐厅ID", "总价", "下单时间"}, 0);
        orderTable = new JTable(orderTableModel);
        JScrollPane scrollPane = new JScrollPane(orderTable);

        // 加载订单数据
        loadOrders();

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton deleteOrderButton = new JButton("删除订单");
        deleteOrderButton.addActionListener(e -> deleteOrder());
        JButton updateOrderButton = new JButton("修改订单");
        updateOrderButton.addActionListener(e -> updateOrder());

        buttonPanel.add(deleteOrderButton);
        buttonPanel.add(updateOrderButton);

        // 将表格和按钮添加到面板
        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        return panel;
    }

    private void updateOrder() {
        int selectedRow = orderTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要修改的订单");
            return;
        }

        // 获取选中的订单
        int orderId = Integer.parseInt(orderTableModel.getValueAt(selectedRow, 0).toString());
        int userId = Integer.parseInt(orderTableModel.getValueAt(selectedRow, 1).toString());
        int restaurantId = Integer.parseInt(orderTableModel.getValueAt(selectedRow, 2).toString());
        double totalPrice = Double.parseDouble(orderTableModel.getValueAt(selectedRow, 3).toString());

        // 弹出对话框让用户修改订单
        JTextField userIdField = new JTextField(String.valueOf(userId));
        JTextField restaurantIdField = new JTextField(String.valueOf(restaurantId));
        JTextField totalPriceField = new JTextField(String.valueOf(totalPrice));
        JPanel inputPanel = new JPanel(new GridLayout(3, 2));
        inputPanel.add(new JLabel("用户 ID:"));
        inputPanel.add(userIdField);
        inputPanel.add(new JLabel("餐厅 ID:"));
        inputPanel.add(restaurantIdField);
        inputPanel.add(new JLabel("总价:"));
        inputPanel.add(totalPriceField);

        int result = JOptionPane.showConfirmDialog(this, inputPanel, "修改订单", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            try {
                // 更新订单
                Order order = new Order();
                order.setId(orderId);
                order.setUserId(Integer.parseInt(userIdField.getText()));
                order.setRestaurantId(Integer.parseInt(restaurantIdField.getText()));
                order.setTotalPrice(Double.parseDouble(totalPriceField.getText()));

                OrderDAO orderDAO = new OrderDAO();
                orderDAO.updateOrder(order);

                JOptionPane.showMessageDialog(this, "订单修改成功！");
                loadOrders(); // 刷新订单表格
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "修改订单失败: " + ex.getMessage());
            }
        }
    }

    private JPanel createReviewPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 输入面板
        JPanel inputPanel = new JPanel(new GridLayout(4, 2));
        inputPanel.add(new JLabel("餐厅:"));
        restaurantComboBox = new JComboBox<>();
        loadRestaurantsToComboBox();
        inputPanel.add(restaurantComboBox);

        inputPanel.add(new JLabel("评分 (1-5):"));
        ratingField = new JTextField();
        inputPanel.add(ratingField);

        inputPanel.add(new JLabel("评论:"));
        commentArea = new JTextArea();
        inputPanel.add(new JScrollPane(commentArea));

        JButton submitReviewButton = new JButton("提交评价");
        submitReviewButton.addActionListener(e -> submitReview());
        inputPanel.add(submitReviewButton);

        // 表格模型
        reviewTableModel = new DefaultTableModel(new String[]{"评价ID", "餐厅ID", "评分", "评论", "评价时间"}, 0);
        reviewTable = new JTable(reviewTableModel);
        JScrollPane scrollPane = new JScrollPane(reviewTable);

        // 加载评价数据
        loadReviews();

        panel.add(inputPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);
        return panel;
    }

    private JPanel createMenuManagementPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 表格模型
        DefaultTableModel menuTableModel = new DefaultTableModel(new String[]{"ID", "餐厅ID", "名称", "价格"}, 0);
        JTable menuTable = new JTable(menuTableModel);
        JScrollPane scrollPane = new JScrollPane(menuTable);

        // 加载菜单数据
        loadMenuItems(menuTableModel);

        // 修改菜单项按钮
        JButton updateMenuItemButton = new JButton("修改菜单项");
        updateMenuItemButton.addActionListener(e -> updateMenuItem(menuTable, menuTableModel));

        // 将表格和按钮添加到面板
        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(updateMenuItemButton, BorderLayout.SOUTH);

        return panel;
    }

    private void loadRestaurants() {
        RestaurantDAO restaurantDAO = new RestaurantDAO();
        List<Restaurant> restaurants = restaurantDAO.getAllRestaurants();
        restaurantTableModel.setRowCount(0); // 清空表格
        for (Restaurant restaurant : restaurants) {
            restaurantTableModel.addRow(new Object[]{
                    restaurant.getId(),
                    restaurant.getName(),
                    restaurant.getLocation(),
                    restaurant.getCuisineType()
            });
        }
    }

    private void loadRestaurantsToComboBox() {
        RestaurantDAO restaurantDAO = new RestaurantDAO();
        List<Restaurant> restaurants = restaurantDAO.getAllRestaurants();
        restaurantComboBox.removeAllItems();
        for (Restaurant restaurant : restaurants) {
            restaurantComboBox.addItem(restaurant.getName());
        }
    }

    private void loadMenuItemsByRestaurant() {
        String restaurantName = (String) restaurantComboBox.getSelectedItem();
        if (restaurantName == null) {
            return;
        }

        try {
            RestaurantDAO restaurantDAO = new RestaurantDAO();
            MenuItemDAO menuItemDAO = new MenuItemDAO();

            // 获取餐厅 ID
            int restaurantId = restaurantDAO.getRestaurantIdByName(restaurantName);
            if (restaurantId == -1) {
                throw new Exception("餐厅不存在");
            }

            // 加载该餐厅的菜单项
            List<MenuItem> menuItems = menuItemDAO.getMenuItemsByRestaurantId(restaurantId);
            menuItemComboBox.removeAllItems(); // 清空下拉框
            for (MenuItem menuItem : menuItems) {
                menuItemComboBox.addItem(menuItem.getName());
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载菜单项失败: " + ex.getMessage());
        }
    }

    private void loadOrders() {
        OrderDAO orderDAO = new OrderDAO();
        List<Order> orders = orderDAO.getOrdersByUserId(userId);
        orderTableModel.setRowCount(0); // 清空表格
        for (Order order : orders) {
            orderTableModel.addRow(new Object[]{
                    order.getId(),
                    order.getUserId(),
                    order.getRestaurantId(),
                    order.getTotalPrice(),
                    order.getOrderDate()
            });
        }
    }

    private void loadReviews() {
        ReviewDAO reviewDAO = new ReviewDAO();
        List<Review> reviews = reviewDAO.getReviewsByUserId(userId);
        reviewTableModel.setRowCount(0); // 清空表格
        for (Review review : reviews) {
            reviewTableModel.addRow(new Object[]{
                    review.getId(),
                    review.getRestaurantId(),
                    review.getRating(),
                    review.getComment(),
                    review.getReviewDate()
            });
        }
    }

    private void loadMenuItems(DefaultTableModel menuTableModel) {
        MenuItemDAO menuItemDAO = new MenuItemDAO();
        List<MenuItem> menuItems = menuItemDAO.getAllMenuItems();
        menuTableModel.setRowCount(0); // 清空表格
        for (MenuItem menuItem : menuItems) {
            menuTableModel.addRow(new Object[]{
                    menuItem.getId(),
                    menuItem.getRestaurantId(),
                    menuItem.getName(),
                    menuItem.getPrice()
            });
        }
    }

    private void placeOrder() {
        String restaurantName = (String) restaurantComboBox.getSelectedItem();
        String menuItemName = (String) menuItemComboBox.getSelectedItem();
        int quantity = (int) quantitySpinner.getValue();

        try {
            RestaurantDAO restaurantDAO = new RestaurantDAO();
            MenuItemDAO menuItemDAO = new MenuItemDAO();
            OrderDAO orderDAO = new OrderDAO();
            OrderItemDAO orderItemDAO = new OrderItemDAO();

            // 获取餐厅 ID
            int restaurantId = restaurantDAO.getRestaurantIdByName(restaurantName);
            if (restaurantId == -1) {
                throw new Exception("餐厅不存在");
            }

            // 获取菜单项 ID 和价格
            int menuItemId = menuItemDAO.getMenuItemIdByName(menuItemName);
            if (menuItemId == -1) {
                throw new Exception("菜单项不存在");
            }
            double price = menuItemDAO.getMenuItemPriceById(menuItemId);

            // 创建订单
            Order order = new Order();
            order.setUserId(userId);
            order.setRestaurantId(restaurantId);
            order.setTotalPrice(price * quantity);
            orderDAO.addOrder(order);

            // 创建订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setMenuItemId(menuItemId);
            orderItem.setQuantity(quantity);
            orderItemDAO.addOrderItem(orderItem);

            JOptionPane.showMessageDialog(this, "下单成功！");
            loadOrders(); // 刷新订单表格
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "下单失败: " + ex.getMessage());
        }
    }

    private void deleteOrder() {
        int selectedRow = orderTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的订单");
            return;
        }

        // 获取选中的订单 ID
        int orderId = (int) orderTableModel.getValueAt(selectedRow, 0);

        // 确认删除
        int confirm = JOptionPane.showConfirmDialog(this, "确定要删除该订单吗？", "删除订单", JOptionPane.YES_NO_OPTION);
        if (confirm == JOptionPane.YES_OPTION) {
            try {
                OrderDAO orderDAO = new OrderDAO();
                OrderItemDAO orderItemDAO = new OrderItemDAO();

                // 先删除订单项，再删除订单
                orderItemDAO.deleteOrderItemsByOrderId(orderId);
                orderDAO.deleteOrder(orderId);

                JOptionPane.showMessageDialog(this, "订单删除成功！");
                loadOrders(); // 刷新订单表格
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "删除订单失败: " + ex.getMessage());
            }
        }
    }

    private void submitReview() {
        String restaurantName = (String) restaurantComboBox.getSelectedItem();
        int rating = Integer.parseInt(ratingField.getText());
        String comment = commentArea.getText();

        try {
            RestaurantDAO restaurantDAO = new RestaurantDAO();
            ReviewDAO reviewDAO = new ReviewDAO();

            int restaurantId = restaurantDAO.getRestaurantIdByName(restaurantName);

            Review review = new Review();
            review.setUserId(userId);
            review.setRestaurantId(restaurantId);
            review.setRating(rating);
            review.setComment(comment);
            reviewDAO.addReview(review);

            JOptionPane.showMessageDialog(this, "评价提交成功！");
            loadReviews(); // 刷新评价表格
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "评价提交失败: " + ex.getMessage());
        }
    }

    private void updateMenuItem(JTable menuTable, DefaultTableModel menuTableModel) {
        int selectedRow = menuTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要修改的菜单项");
            return;
        }

        // 获取选中的菜单项
        int menuItemId = (int) menuTableModel.getValueAt(selectedRow, 0);
        String name = (String) menuTableModel.getValueAt(selectedRow, 2);
        double price = (double) menuTableModel.getValueAt(selectedRow, 3);

        // 弹出对话框让用户修改菜单项
        JTextField nameField = new JTextField(name);
        JTextField priceField = new JTextField(String.valueOf(price));
        JPanel inputPanel = new JPanel(new GridLayout(2, 2));
        inputPanel.add(new JLabel("名称:"));
        inputPanel.add(nameField);
        inputPanel.add(new JLabel("价格:"));
        inputPanel.add(priceField);

        int result = JOptionPane.showConfirmDialog(this, inputPanel, "修改菜单项", JOptionPane.OK_CANCEL_OPTION);
        if (result == JOptionPane.OK_OPTION) {
            try {
                // 更新菜单项
                MenuItem menuItem = new MenuItem();
                menuItem.setId(menuItemId);
                menuItem.setName(nameField.getText());
                menuItem.setPrice(Double.parseDouble(priceField.getText()));

                MenuItemDAO menuItemDAO = new MenuItemDAO();
                menuItemDAO.updateMenuItem(menuItem);

                JOptionPane.showMessageDialog(this, "菜单项修改成功！");
                loadMenuItems(menuTableModel); // 刷新菜单表格
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "修改菜单项失败: " + ex.getMessage());
            }
        }
    }

    private JPanel createDeliveryPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 表格模型
        DefaultTableModel orderTableModel = new DefaultTableModel(new String[]{"订单ID", "餐厅ID", "总价", "下单时间", "派送员ID"}, 0);
        JTable orderTable = new JTable(orderTableModel);
        JScrollPane orderScrollPane = new JScrollPane(orderTable);

        // 加载订单数据
        loadOrdersForDelivery(orderTableModel);

        // 派送员选择下拉框
        JComboBox<String> deliveryPersonComboBox = new JComboBox<>();
        loadDeliveryPersons(deliveryPersonComboBox);

        // 派送按钮
        JButton assignDeliveryButton = new JButton("派送订单");
        assignDeliveryButton.addActionListener(e -> assignDelivery(orderTable, deliveryPersonComboBox));

        // 输入面板
        JPanel inputPanel = new JPanel(new GridLayout(2, 2));
        inputPanel.add(new JLabel("选择派送员:"));
        inputPanel.add(deliveryPersonComboBox);
        inputPanel.add(new JLabel(""));
        inputPanel.add(assignDeliveryButton);

        // 将表格和输入面板添加到主面板
        panel.add(orderScrollPane, BorderLayout.CENTER);
        panel.add(inputPanel, BorderLayout.SOUTH);

        return panel;
    }

    private void loadOrdersForDelivery(DefaultTableModel orderTableModel) {
        OrderDAO orderDAO = new OrderDAO();
        List<Order> orders = orderDAO.getAllOrders();
        orderTableModel.setRowCount(0); // 清空表格
        for (Order order : orders) {
            orderTableModel.addRow(new Object[]{
                    order.getId(),
                    order.getRestaurantId(),
                    order.getTotalPrice(),
                    order.getOrderDate(),
                    order.getDeliveryPersonId() // 添加派送员 ID
            });
        }
    }

    private void loadDeliveryPersons(JComboBox<String> deliveryPersonComboBox) {
        DeliveryPersonDAO deliveryPersonDAO = new DeliveryPersonDAO();
        List<DeliveryPerson> deliveryPersons = deliveryPersonDAO.getAllDeliveryPersons(); // 加载所有派送员
        deliveryPersonComboBox.removeAllItems();
        for (DeliveryPerson deliveryPerson : deliveryPersons) {
            deliveryPersonComboBox.addItem(deliveryPerson.getName() + " (" + deliveryPerson.getLocation() + ")");
        }
    }

    private void assignDelivery(JTable orderTable, JComboBox<String> deliveryPersonComboBox) {
        int selectedRow = orderTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要派送的订单");
            return;
        }

        int selectedDeliveryPersonIndex = deliveryPersonComboBox.getSelectedIndex();
        if (selectedDeliveryPersonIndex == -1) {
            JOptionPane.showMessageDialog(this, "请选择派送员");
            return;
        }

        // 获取选中的订单 ID
        int orderId = (int) orderTable.getModel().getValueAt(selectedRow, 0);

        // 获取选中的派送员 ID
        DeliveryPersonDAO deliveryPersonDAO = new DeliveryPersonDAO();
        List<DeliveryPerson> deliveryPersons = deliveryPersonDAO.getAllDeliveryPersons();
        int deliveryPersonId = deliveryPersons.get(selectedDeliveryPersonIndex).getId();

        // 派送订单
        try {
            OrderDAO orderDAO = new OrderDAO();
            orderDAO.assignDeliveryPerson(orderId, deliveryPersonId);

            // 更新派送员状态为忙碌
            deliveryPersonDAO.updateDeliveryPersonStatus(deliveryPersonId, "忙碌");

            JOptionPane.showMessageDialog(this, "订单派送成功！");
            loadDeliveryPersons(deliveryPersonComboBox); // 刷新派送员列表
        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "派送订单失败: " + ex.getMessage());
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new MainFrame(1).setVisible(true); // 假设用户 ID 为 1
        });
    }
}
